import React, {Fragment} from 'react';
import Page from 'src/routes/Page';
import {autobind} from 'core-decorators';
import StandardTable from 'src/components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import QueryData from 'src/components/queryData/QueryData';
import OperateModelView from 'src/components/operateModelView/OperateModelView';
import BasicModelView from 'src/components/basicModelView/BasicModelView';
import Selector from 'src/components/selector/Selector';
import {Card, Button, Input, Form, message, Icon, InputNumber} from 'antd';
import {connect} from 'dva/index';

const FormItem = Form.Item;

message.config({
  top: 300,
});

@connect(({OemDict, loading}) => ({
  OemDict,
  loading: loading.models.OemDict,
}))
@Form.create()
@autobind
class OemDict extends Page {
  constructor(props) {
    super(props);
    let oemData = JSON.parse(localStorage.getItem('oemData')); //搜索列表用的
    this.oemObj = JSON.parse(localStorage.getItem('oemObj')); //列表展示 根据oemid兑换成站点名称
    this.state = {
      paging: {},
      oemResults: [],
      selectedRows: [],
      modifyShow: false,
      formValues: {},
      addShow: false,
      addShowItem: false,
      shrink: true,
      dictTypes: [],
      queryFromValue: null,
      deleteShowChoose: false,
      oemData,//搜索列表 站点名称
      showBtn: false,
      OneShowRevert: false,
      ShowRevert: false,
    };

  }

  componentDidMount() {
    this.dispatch({
      type: 'OemDict/getOemDictList',
    });
    this.dispatch({
      type: 'OemDict/oemFindType',
    });
  }

  shouldComponentUpdate(props, state) {
    let {OemDict} = props;

    let {
      getOemDictListResult,
      getOemDictIdResult,
      updateDictListResult,
      checkOemDictResult,
      saveOemDictResult,
      oemFindTypeResult,
      searchTypeResult,
      recoverySingleByIdResult,
      updateByStationIdResult,
    } = OemDict;

    this.rollout(
      getOemDictListResult,
      false,
      (result, msg, paging) => {
        this.state.oemResults = result.map(item => ({...item, oemName: this.oemObj[item.oemId]}));
        this.state.paging = paging;
        this.state.selectedRows = [];
      },
      false
    );

    this.rollout(
      searchTypeResult,
      false,
      (result, msg, paging) => {
        this.state.oemResults = result;
        this.state.paging = paging;
      },
      false
    );

    this.rollout(
      getOemDictIdResult,
      false,
      (result, msg, paging) => {
        this.state.formValues = result;
        this.state.modifyShow = true;
      },
      false
    );

    this.rollout(
      recoverySingleByIdResult,
      false,
      (result, msg, paging) => {
        this.state.OneShowRevert = false;
        this.toast('还原成功');

      },
      false
    );

    this.rollout(
      updateByStationIdResult,
      false,
      (result, msg, paging) => {
        this.toast('站点还原成功');
      },
      false
    );

    this.rollout(
      updateDictListResult,
      false,
      (result, msg, paging) => {
        this.state.modifyShow = false;
        message.info('已修改');
        this.dispatch({
          type: 'OemDict/getOemDictList',
          payload: {
            ...this.state.queryFromValue,
            current: this.state.paging.current,
            size: this.state.paging.pageSize,
          }
        });
      },
      msg => {
        this.state.modifyShow = false;
        message.info(msg.message);
      }
    );

    this.rollout(
      checkOemDictResult,
      false,
      (result, msg, paging) => {
        this.dispatch({
          type: 'OemDict/saveOemDict',
          payload: this.state.formValues,
        });
      },
      msg => {}
    );

    this.rollout(
      saveOemDictResult,
      false,
      (result, msg, paging) => {
        this.state.addShowItem = false;
        this.dispatch({
          type: 'OemDict/getOemDictList',
          payload: {
            ...this.state.queryFromValue,
            current: this.state.paging.current,
            size: this.state.paging.pageSize,
          }
        });
        message.info('已添加');
      },
      msg => {
        this.state.addShowItem = false;
        message.info(msg.message);
      }
    );

    this.rollout(
      oemFindTypeResult,
      false,
      (result, msg, paging) => {
        let list = result.map((item, index) => ({value: item, label: item}));
        this.state.dictTypes = list;
      },
      false
    );


    return this.equal(props, state);
  }

  render() {
    const {
      paging,
      oemResults,
      selectedRows,
      formValues,
      addShowItem,
      modifyShow,
      shrink,
      oemData,
      dictTypes,
      showBtn,
      queryFromValue,
      OneShowRevert,
      ShowRevert,
    } = this.state;

    const formListAddItem = queryFromValue ? [
      {
        label: '站点',
        value: 'oemName',
        rules: [],
        initialValue: this.oemObj[queryFromValue.oemId],
        renderItem: <Input disabled/>,
        //
      },
      {
        label: '大类',
        value: 'type',
        rules: [],
        initialValue: queryFromValue && queryFromValue.type,
        renderItem: <Input disabled/>,
        //
      },
      {
        label: '小类',
        value: 'label',
        rules: [],
        renderItem: <Input placeholder="请输入小类"/>,
      },
      {
        label: '排序',
        value: 'sort',
        rules: [],
        renderItem: <InputNumber min={1} defaultValue={500} style={{width: '217px'}}/>,
      },
      {
        label: '值',
        value: 'value',
        rules: [],
        renderItem: <Input placeholder="请输入输入值"/>,
      },
    ] : null;

    // table 显示列表
    const columns = [
      {
        title: '站点', // 列表显示
        dataIndex: 'oemName', // 数据展示对应字段
      },
      {
        title: '大类', // 列表显示
        dataIndex: 'type', // 数据展示对应字段
      },
      {
        title: '小类',
        dataIndex: 'label',
      },
      {
        title: '值',
        dataIndex: 'value',
        render: (text, record, index) => (
          <p>{record.value.length > 15 ? record.value.substr(0, 15) + '...' : record.value}</p>
        ),
      },
      {
        title: '描述',
        dataIndex: 'description',
        render: (text, record, index) => (
          <p>
            {record.description.length > 15
              ? record.description.substr(0, 15) + '...'
              : record.description}
          </p>
        ),
      },
      {
        title: '操作',
        render: (text, record, index) => (
          <Fragment>
            <Button type="primary" onClick={() => this.showUpdateView(text, record, index)}>
              修改
            </Button>
            <Button
              type="danger"
              style={{marginLeft: '5px'}}
              onClick={() => this.oneKeyRevert(text, record, index)}
            >
              一键还原
            </Button>
          </Fragment>
        ),
      },
    ];

    const formList = [
      {
        label: '大类',
        value: 'type',
        rules: [
          {
            required: true,
            message: '大类不能为空',
          },
        ],
        initialValue: formValues && formValues.type,
        renderItem: <Input placeholder="请输入大类" disabled/>,
      },
      {
        label: '小类',
        value: 'label',
        rules: [],
        initialValue: formValues && formValues.label,
        renderItem: <Input placeholder="请输入小类" disabled/>,
      },
      {
        label: '排序',
        value: 'sort',
        rules: [],
        initialValue: formValues && formValues.sort,
        renderItem: <InputNumber min={1} defaultValue={500} style={{width: '217px'}}/>,
      },
      {
        label: '值',
        value: 'value',
        rules: [],
        initialValue: formValues && formValues.value,
        renderItem: <Input placeholder="请输入输入值"/>,
      },

      {
        label: '描述',
        value: 'description',
        initialValue: formValues && formValues.description,
        renderItem: <textarea placeholder="请输入描述" style={{width: '217px'}}/>,
      },
    ];

    //放置批量操作的按鈕
    const menu = null;

    // 渲染按钮内容
    const button = showBtn ? (
      <span>
        <Button type="primary" style={{marginRight: '10px'}} onClick={this.addItem}>
          增加
        </Button>
         <Button type="primary" style={{marginRight: '10px'}} onClick={this.revertStation}>
          还原站点
        </Button>
      </span>
    ) : null;


    // 查询显示列表
    const searchList = [
      {
        value: 'oemId',
        renderItem: <Selector placeholder="请选择站点" selectList={oemData}/>,
      },
      {
        value: 'type',
        renderItem: <Selector placeholder="请选择大类" selectList={dictTypes}/>,
      },
    ];

    return (
      <PageHeaderLayout title="站点字典管理">
        <Card bordered={false}>
          <QueryData
            shrink={shrink}
            queryList={searchList}
            selectedRows={selectedRows}
            onQuery={this.onQuery}
            operateExtra={button}
            menuExtra={menu}
          />

          {/*渲染列表内容*/}
          <StandardTable
            rowShow={false}
            paging={paging}
            selectedRows={selectedRows}
            loading={this.props.loading}
            columns={columns}
            data={oemResults}
            onSelectRow={this._onSelectRow}
            onChange={this._onChange}
          />
        </Card>

        {addShowItem && (
          <OperateModelView
            visible={addShowItem}
            title="新增字典小类"
            onCancel={() => this.setState({addShowItem: false})}
            formItemList={formListAddItem}
            formData={formValues}
            onSubmit={this.save}
          />
        )}

        {modifyShow && (
          <OperateModelView
            visible={modifyShow}
            title="修改字典信息"
            onCancel={() => this.setState({modifyShow: false})}
            formItemList={formList}
            formData={formValues}
            onSubmit={this.update}
          />
        )}

        {OneShowRevert && (
          <BasicModelView
            visible={OneShowRevert}
            title="确定重置该站点信息?"
            extra={<div>确认重置？</div>}
            onCancel={() => this.setState({OneShowRevert: false})}
            onOk={this.oneBtn}
          />
        )}

        {ShowRevert && (
          <BasicModelView
            visible={ShowRevert}
            title="确定重置站点信息?"
            extra={<div>确认重置？</div>}
            onCancel={() => this.setState({ShowRevert: false})}
            onOk={this.RevertBtn}
          />
        )}

      </PageHeaderLayout>
    );
  }

  // 行选择
  _onSelectRow(row) {
    this.setState({
      selectedRows: row,
    });
  }

  // 分页 过滤 排序
  _onChange(page, filter, sort) {
    const {queryFromValue} = this.state;
    this.state.selectedRows = [];
    this.dispatch({
      type: 'OemDict/getOemDictList',
      payload: {
        ...queryFromValue,
        current: page.current,
        size: page.pageSize,
      },
    });
  }

  // 显示修改弹窗
  // text 为当前行的值
  // record 为当前行数据
  // index 为当前行索引
  showUpdateView(text, record, index) {
    //  获取详情
    this.dispatch({
      type: 'OemDict/getOemDictId',
      payload: record.id,
    });
  }

  update(formValues) {
    this.dispatch({
      type: 'OemDict/updateDictList',
      payload: {
        ...formValues,
      },
    });
  }

  oneBtn() {
    let {formValues} = this.state;
    this.dispatch({
      type: 'OemDict/recoverySingleById',
      payload: formValues.id,
    });
  }

  oneKeyRevert(text, record, index) {
    this.setState({OneShowRevert: true, formValues: record});
  }

  addItem() {
    let {queryFromValue} = this.state;
    this.setState({formValues: {}, addShowItem: true});
  }

  RevertBtn() {
    let {queryFromValue} = this.state;
    this.dispatch({
      type: 'OemDict/updateByStationId',
      payload: {
        stationId: queryFromValue.oemId
      },
    });
  }

  revertStation() {
    this.setState({ShowRevert: true});
  }

  save(formValues) {
    let {queryFromValue} = this.state;
    formValues = {...formValues, ...queryFromValue}
    this.setState({formValues}, () => this.dispatch({
      type: 'OemDict/checkOemDict',
      payload: {
        ...formValues,
      },
    }));
  }

  //  查询方法
  onQuery(formValues) {
    if (formValues.oemId && formValues.type) {
      this.setState({
        showBtn: true,
        queryFromValue: formValues,
      })
    } else {
      this.setState({
        showBtn: false,
        queryFromValue: formValues,
      })
    }

    this.dispatch({
      type: 'OemDict/getOemDictList',
      payload: {
        ...formValues,
      }
    });
  }
}

export default OemDict;
